package com.yuqih.common.dao.impl;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.GenericTypeResolver;
import org.springframework.util.Assert;

import com.yuqih.common.config.IFrameworkConfigInitializing;
import com.yuqih.common.dao.IBaseDao;
import com.yuqih.common.dao.ICommonDao;
import com.yuqih.common.dto.PageMetadata;

public abstract class BaseDao<T, K, C> implements IBaseDao<T, K, C> {

	private final Class<T> type;
	private final Class<C> conditionType;

	@Autowired
	protected ICommonDao commonDao;
	
	@Autowired
	private IFrameworkConfigInitializing frameworkConfigInitializing;

	@SuppressWarnings("unchecked")
	public BaseDao() {
		super();
		Class<?>[] types = GenericTypeResolver.resolveTypeArguments(getClass(), IBaseDao.class);
		Assert.notNull(types, "无法解析泛型");
		this.type = (Class<T>) types[0];
		this.conditionType = (Class<C>) types[2];
	}
	
	protected BaseDao(Class<T> type, Class<C> conditionType) {
		super();
		this.type = type;
		this.conditionType = conditionType;
	}
	
	@PostConstruct
	public void init() {
		frameworkConfigInitializing.registerBaseDao(type, this, conditionType);
	}

	@Override
	public int insert(T entity) {
		return commonDao.insert(type, entity);
	}
	
	@Override
	public int insertBatch(List<T> entities) {
		return commonDao.insertBatch(type, entities);
	}

	@Override
	public int update(T entity) {
		return commonDao.update(type, entity);
	}
	
	@Override
	public int updateBatch(List<T> entities) {
		return commonDao.updateBatch(type, entities);
	}

	@Override
	public int delete(K id) {
		return commonDao.delete(type, id);
	}

	@Override
	public T selectById(K id) {
		return commonDao.selectById(type, id);
	}
	
	@Override
	public int deleteBatch(List<K> ids) {
		return commonDao.deleteBatch(type, ids);
	}

	@Override
	public List<T> selectList(C condition) {
		return commonDao.selectList(type, condition, null);
	}

	@Override
	public List<T> selectList(C condition, PageMetadata pageMetadata) {
		return commonDao.selectList(type, condition, pageMetadata);
	}

	@Override
	public int count(C condition) {
		return commonDao.count(type, condition);
	}

}
